package com.qiangesoft.blog.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.blog.common.constants.FieldConstants;
import com.qiangesoft.blog.common.mvc.PageQuery;
import com.qiangesoft.blog.common.mvc.PageResultVO;
import com.qiangesoft.blog.system.entity.SysDict;
import com.qiangesoft.blog.system.entity.SysDictData;
import com.qiangesoft.blog.system.exception.BusinessException;
import com.qiangesoft.blog.system.mapper.SysDictDataMapper;
import com.qiangesoft.blog.system.pojo.vo.DictDataVO;
import com.qiangesoft.blog.system.service.ISysDictDataService;
import com.qiangesoft.blog.system.service.ISysDictService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qiangesoft.blog.common.constants.FieldConstants.LIMIT_ONE;
import static com.qiangesoft.blog.common.enums.PublishEnum.PUBLISH;
import static com.qiangesoft.blog.common.result.ResultCode.DATA_TAG_IS_EXIST;

/**
 * <p>
 * 字典数据 服务实现类
 * </p>
 *
 * @author qiange
 * @since 2023-06-01
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

    private final ISysDictService sysDictService;

    @Override
    public PageResultVO<SysDictData> listDictData(PageQuery pageQuery, Long dictId, Boolean isPublish) {
        PageResultVO<SysDictData> pageResultVO = new PageResultVO<>();
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        pageResultVO.setPageNum(pageNum);
        pageResultVO.setPageSize(pageSize);

        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<SysDictData>()
                .eq(FieldConstants.DICT_TYPE_ID, dictId)
                .eq(isPublish != null, FieldConstants.IS_PUBLISH, isPublish);

        Page<SysDictData> dictDataPage = baseMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        dictDataPage.getRecords().forEach(item -> {
            SysDict dict = sysDictService.getById(item.getDictId());
            item.setDict(dict);
        });
        pageResultVO.setTotal(dictDataPage.getTotal());
        pageResultVO.setPages(dictDataPage.getPages());
        pageResultVO.setResults(dictDataPage.getRecords());
        return pageResultVO;
    }

    @Override
    public void insertDictData(SysDictData dictData) {
        // 判断添加的字典数据是否存在
        isExist(dictData);
        baseMapper.insert(dictData);
    }

    @Override
    public void updateDictData(SysDictData sysDictData) {
        SysDictData dictData = baseMapper.selectOne(new QueryWrapper<SysDictData>().eq(FieldConstants.DICT_LABEL, sysDictData.getLabel()));
        if (dictData != null && !dictData.getId().equals(sysDictData.getId())) {
            throw new BusinessException("该标签已存在!");
        }
        baseMapper.updateById(sysDictData);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public void deleteDictData(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public Map<String, DictDataVO> getDataByDictType(List<String> types) {
        Map<String, DictDataVO> map = new HashMap<>();
        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(FieldConstants.TYPE, types).eq(FieldConstants.IS_PUBLISH, PUBLISH.getCode());
        List<SysDict> dictList = sysDictService.list(queryWrapper);
        dictList.forEach(item -> {
            QueryWrapper<SysDictData> sysDictDataQueryWrapper = new QueryWrapper<>();
            sysDictDataQueryWrapper.eq(FieldConstants.IS_PUBLISH, PUBLISH.getCode());
            sysDictDataQueryWrapper.eq(FieldConstants.DICT_TYPE_ID, item.getId());
            sysDictDataQueryWrapper.orderByAsc(FieldConstants.SORT);
            List<SysDictData> dataList = baseMapper.selectList(sysDictDataQueryWrapper);
            String defaultValue = null;
            for (SysDictData dictData : dataList) {
                // 选取默认值
                if (dictData.getIsDefault()) {
                    defaultValue = dictData.getValue();
                    break;
                }
            }
            DictDataVO result = new DictDataVO();
            result.setDefaultValue(defaultValue);
            result.setList(dataList);
            map.put(item.getType(), result);
        });
        return map;
    }

    /**
     * 校验是否存在
     *
     * @param dictData
     */
    public void isExist(SysDictData dictData) {
        SysDictData temp = baseMapper.selectOne(new QueryWrapper<SysDictData>()
                .eq(FieldConstants.DICT_LABEL, dictData.getLabel())
                .eq(FieldConstants.DICT_TYPE_ID, dictData.getDictId())
                .last(LIMIT_ONE));
        Assert.notNull(temp, DATA_TAG_IS_EXIST.getDesc());
    }
}
